<template>
  <div class="space-y-6">
    <!-- 搜索和筛选 -->
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2"
            >用户名</label
          >
          <InputText
            v-model="searchForm.username"
            placeholder="搜索用户名"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2"
            >问卷标题</label
          >
          <InputText
            v-model="searchForm.questionnaireTitle"
            placeholder="搜索问卷标题"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2"
            >状态</label
          >
          <Dropdown
            v-model="searchForm.status"
            :options="statusOptions"
            optionLabel="label"
            optionValue="value"
            placeholder="选择状态"
            class="w-full"
          />
        </div>
        <div class="flex items-end">
          <Button
            label="搜索"
            icon="pi pi-search"
            @click="searchRecords"
            class="mr-2"
          />
          <Button
            label="导出"
            icon="pi pi-file-excel"
            severity="secondary"
            @click="exportRecords"
          />
        </div>
      </div>
    </div>

    <!-- 答题记录列表 -->
    <div
      class="bg-white rounded-lg shadow-sm p-6 h-[calc(100vh-254px)] overflow-y-auto grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6"
    >
      <div v-for="record in answerRecords" :key="record.id" class="group">
        <div class="bg-gradient-to-br from-white to-gray-50 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 border border-gray-100 overflow-hidden">
          <!-- 卡片头部 -->
          <div class="bg-gradient-to-r from-blue-500 to-purple-600 px-4 py-3 text-white">
            <div class="flex items-center justify-between">
              <div class="flex justify-between items-center w-full">
                <h3 class="text-base font-bold">{{ record.username }}</h3>
                <p class="text-blue-100 text-xs opacity-90">{{ record.createTime }}</p>
              </div>
            </div>
          </div>

          <div class="p-3">
            <div class="space-y-2">
              <div
                v-for="(userAnswer, index) in getPersonalityResults(record.userAnswerList)"
                :key="userAnswer.questionnaireId"
                class="group/item"
              >
                <div class="bg-gray-50 rounded-md px-3 py-2 hover:bg-gray-100 transition-colors duration-200">
                  <!-- 人格维度标题和系数 -->
                  <div class="flex items-center justify-between mb-1">
                    <div class="flex items-center space-x-2">
                      <div 
                        class="w-2.5 h-2.5 rounded-full"
                        :style="{ backgroundColor: getPersonalityColor(index) }"
                      ></div>
                      <span class="font-medium text-gray-800 text-sm">
                        {{ getPersonalityName(userAnswer.questionnaireTitle) }}
                      </span>
                    </div>
                    <div class="flex items-center space-x-2">
                      <div class="text-sm font-bold" :style="{ color: getPersonalityColor(index) }">
                        {{ userAnswer.reNum ? userAnswer.reNum.toFixed(2) : 'N/A' }}
                      </div>
                      <button
                        class="text-xs px-1.5 py-0.5 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors duration-200 opacity-0 group-hover/item:opacity-100"
                        @click="viewDetailList(userAnswer.id)"
                      >
                        详情
                      </button>
                    </div>
                  </div>
                  
                  <!-- 进度条和水平标签 -->
                  <div class="flex items-center space-x-2">
                    <div class="flex-1">
                      <div class="w-full bg-gray-200 rounded-full h-1.5">
                        <div 
                          class="h-1.5 rounded-full transition-all duration-500"
                          :style="{ 
                            width: getProgressWidth(userAnswer.reNum) + '%',
                            backgroundColor: getPersonalityColor(index)
                          }"
                        ></div>
                      </div>
                    </div>
                    <span 
                      class="inline-block px-1.5 py-0.5 rounded text-xs font-medium min-w-[36px] text-center"
                      :style="{ 
                        backgroundColor: getPersonalityColor(index) + '20',
                        color: getPersonalityColor(index)
                      }"
                    >
                      {{ getLevelLabel(userAnswer.reNum) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 综合评分 -->
            <div v-if="record.userAnswerList.length === 5" class="mt-3 px-3 py-2 bg-gradient-to-r from-blue-50 to-purple-50 rounded-md border border-blue-100">
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-1.5">
                  <i class="pi pi-star text-yellow-500 text-sm"></i>
                  <span class="text-xs font-medium text-gray-700">综合评分</span>
                </div>
                <div class="text-lg font-bold text-blue-600">
                  {{ calculateOverallScore(record.userAnswerList) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 答题记录详情对话框 -->
    <Dialog
      v-model:visible="showDetailDialog"
      header="答题记录详情"
      modal
      class="w-full max-w-6xl"
    >
      <div v-if="selectedRecord" class="space-y-6">
        <!-- 基本信息 -->
        <div class="bg-gray-50 p-4 rounded-lg">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">基本信息</h3>
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >用户</label
              >
              <p class="mt-1 text-gray-900">{{ selectedRecord.username }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >问卷</label
              >
              <p class="mt-1 text-gray-900">
                {{ selectedRecord.questionnaireTitle }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >得分</label
              >
              <p
                class="mt-1 font-semibold"
                :class="getScoreColor(selectedRecord.score)"
              >
                {{ selectedRecord.score || "-" }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >答题时间</label
              >
              <p class="mt-1 text-gray-900">
                {{ formatDate(selectedRecord.answerTime) }}
              </p>
            </div>
          </div>
        </div>

        <!-- 答题详情 -->
        <div>
          <h3 class="text-lg font-semibold text-gray-900 mb-4">答题详情</h3>
          <div class="space-y-4">
            <div
              v-for="(answer, index) in selectedRecord.answers"
              :key="index"
              class="border rounded-lg p-4"
            >
              <div class="flex justify-between items-start mb-2">
                <h4 class="font-medium text-gray-900">第 {{ index + 1 }} 题</h4>
                <Tag
                  :value="answer.isCorrect ? '正确' : '错误'"
                  :severity="answer.isCorrect ? 'success' : 'danger'"
                />
              </div>
              <p class="text-gray-700 mb-2">{{ answer.questionTitle }}</p>
              <div class="text-sm text-gray-600">
                <div>用户答案: {{ answer.userAnswer }}</div>
                <div>正确答案: {{ answer.correctAnswer }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Dialog>

    <!-- 答题分析对话框 -->
    <Dialog
      v-model:visible="showAnalysisDialog"
      header="答题分析"
      modal
      class="w-full max-w-4xl"
    >
      <div v-if="selectedRecord" class="space-y-6">
        <!-- 统计图表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="bg-white p-4 rounded-lg border">
            <h4 class="font-medium text-gray-900 mb-4">答题正确率</h4>
            <div class="text-center">
              <div class="text-3xl font-bold text-blue-600">
                {{ calculateAccuracy(selectedRecord) }}%
              </div>
              <div class="text-sm text-gray-600 mt-2">
                正确 {{ selectedRecord.correctAnswers || 0 }} / 总计
                {{ selectedRecord.totalQuestions || 0 }}
              </div>
            </div>
          </div>
          <div class="bg-white p-4 rounded-lg border">
            <h4 class="font-medium text-gray-900 mb-4">答题用时</h4>
            <div class="text-center">
              <div class="text-3xl font-bold text-green-600">
                {{ formatDuration(selectedRecord.duration) }}
              </div>
              <div class="text-sm text-gray-600 mt-2">
                平均每题 {{ calculateAverageTime(selectedRecord) }} 秒
              </div>
            </div>
          </div>
        </div>

        <!-- 题目分析 -->
        <div>
          <h4 class="font-medium text-gray-900 mb-4">题目分析</h4>
          <div class="space-y-3">
            <div
              v-for="(answer, index) in selectedRecord.answers"
              :key="index"
              class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
            >
              <div class="flex items-center space-x-3">
                <span class="text-sm font-medium text-gray-700"
                  >第 {{ index + 1 }} 题</span
                >
                <Tag
                  :value="answer.isCorrect ? '正确' : '错误'"
                  :severity="answer.isCorrect ? 'success' : 'danger'"
                />
              </div>
              <div class="text-sm text-gray-600">
                用时: {{ answer.answerTime || "-" }} 秒
              </div>
            </div>
          </div>
        </div>
      </div>
    </Dialog>

    <!-- 详细答题记录对话框 -->
    <Dialog
      v-model:visible="showDetailListDialog"
      header="详细答题记录"
      modal
      class="w-full max-w-6xl"
    >
      <DataTable
        :value="detailList"
        :paginator="false"
        :rows="10"
        :rowsPerPageOptions="[5, 10, 20, 50]"
        class="p-0 h-[500px]"
        stripedRows
        responsiveLayout="scroll"
        scrollable
        scrollHeight="450px"
        showGridlines
      >
        <Column
          field="questionTitle"
          header="题目内容"
          style="min-width: 400px"
        >
          <template #body="{ data }">
            <div class="text-sm text-gray-900 leading-relaxed max-w-md">
              {{ data.questionTitle }}
            </div>
          </template>
        </Column>
        <Column
          field="optionContent"
          header="选项内容"
          style="min-width: 150px"
        >
          <template #body="{ data }">
            <div class="text-sm text-gray-700">
              {{ data.optionContent }}
            </div>
          </template>
        </Column>

        <Column
          field="optionFactorValue"
          header="题目难度"
          style="width: 120px"
        >
          <template #body="{ data }">
            <span
              class="font-mono text-sm px-2 py-1 rounded"
              :class="getFactorValueClass(data.optionFactorValue)"
            >
              {{ data.optionFactorValue?.toFixed(3) || "N/A" }}
            </span>
          </template>
        </Column>

        <Column field="reNum" header="能力值"  style="width: 100px">
          <template #body="{ data }">
            <span
              class="font-mono text-sm px-2 py-1 rounded"
              :class="getReNumClass(data.reNum)"
            >
              {{ data.reNum?.toFixed(3) || "N/A" }}
            </span>
          </template>
        </Column>

        <Column field="seNum" header="SE值" style="width: 100px">
          <template #body="{ data }">
            <span
              class="font-mono text-sm px-2 py-1 rounded"
              :class="getSeNumClass(data.seNum)"
            >
              {{ data.seNum?.toFixed(3) || "N/A" }}
            </span>
          </template>
        </Column>
      </DataTable>
    </Dialog>

    <!-- 单个答题详情对话框 -->
    <Dialog
      v-model:visible="showAnswerDetailDialog"
      header="答题详情"
      modal
      class="w-full max-w-2xl"
    >
      <div v-if="selectedAnswerDetail" class="space-y-6">
        <!-- 基本信息 -->
        <div class="bg-gray-50 p-4 rounded-lg">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">基本信息</h3>
          <div class="grid grid-cols-2 gap-4 text-sm">
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >题目ID</label
              >
              <p class="mt-1 font-mono text-gray-900">
                {{ selectedAnswerDetail.questionId }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >选项ID</label
              >
              <p class="mt-1 font-mono text-gray-900">
                {{ selectedAnswerDetail.optionId }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >因子值</label
              >
              <p class="mt-1 font-mono text-gray-900">
                {{
                  selectedAnswerDetail.optionFactorValue?.toFixed(3) || "N/A"
                }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >RE值</label
              >
              <p class="mt-1 font-mono text-gray-900">
                {{ selectedAnswerDetail.reNum?.toFixed(3) || "N/A" }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >SE值</label
              >
              <p class="mt-1 font-mono text-gray-900">
                {{ selectedAnswerDetail.seNum?.toFixed(3) || "N/A" }}
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700"
                >题目类型</label
              >
              <p class="mt-1 text-gray-900">
                {{
                  selectedAnswerDetail.questionType === 0 ? "单选题" : "其他"
                }}
              </p>
            </div>
          </div>
        </div>

        <!-- 题目内容 -->
        <div>
          <h3 class="text-lg font-semibold text-gray-900 mb-4">题目内容</h3>
          <div class="bg-white p-4 rounded border">
            <p class="text-gray-900 leading-relaxed">
              {{ selectedAnswerDetail.questionTitle }}
            </p>
          </div>
        </div>

        <!-- 选项内容 -->
        <div>
          <h3 class="text-lg font-semibold text-gray-900 mb-4">选择的选项</h3>
          <div class="bg-blue-50 p-4 rounded border">
            <p class="text-gray-900 font-medium">
              {{ selectedAnswerDetail.optionContent }}
            </p>
          </div>
        </div>

        <!-- 因子值分析 -->
        <div>
          <h3 class="text-lg font-semibold text-gray-900 mb-4">因子值分析</h3>
          <div class="bg-white p-4 rounded border">
            <div class="flex items-center justify-between mb-2">
              <span class="text-sm font-medium text-gray-700">当前因子值:</span>
              <span
                class="font-mono text-lg font-bold px-3 py-1 rounded"
                :class="
                  getFactorValueClass(selectedAnswerDetail.optionFactorValue)
                "
              >
                {{
                  selectedAnswerDetail.optionFactorValue?.toFixed(3) || "N/A"
                }}
              </span>
            </div>
            <div class="text-sm text-gray-600">
              <p
                v-if="selectedAnswerDetail.optionFactorValue >= 4.0"
                class="text-red-600"
              >
                ⚠️ 高因子值：表示该选项反映的问题程度较高
              </p>
              <p
                v-else-if="selectedAnswerDetail.optionFactorValue >= 3.0"
                class="text-orange-600"
              >
                ⚠️ 中等因子值：表示该选项反映的问题程度中等
              </p>
              <p
                v-else-if="selectedAnswerDetail.optionFactorValue >= 2.0"
                class="text-yellow-600"
              >
                ℹ️ 较低因子值：表示该选项反映的问题程度较低
              </p>
              <p v-else class="text-green-600">
                ✅ 低因子值：表示该选项反映的问题程度很低
              </p>
            </div>
          </div>
        </div>
      </div>
    </Dialog>

    <!-- 确认删除对话框 -->
    <ConfirmDialog />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { userAnswerApi } from "@/api/userAnswer.js";
import { useToast } from "primevue/usetoast";

// PrimeVue 组件
import Button from "primevue/button";
import InputText from "primevue/inputtext";
import Dropdown from "primevue/dropdown";
import Calendar from "primevue/calendar";
import DataTable from "primevue/datatable";
import Column from "primevue/column";
import Tag from "primevue/tag";
import Dialog from "primevue/dialog";
import ConfirmDialog from "primevue/confirmdialog";
import { useRoute } from "vue-router";

const toast = useToast();

const route = useRoute()
const currentSystem = computed(() => {
  return route.path.startsWith('/backstage/five') ? 'five' : route.path.startsWith('/backstage/pmpu-scale') ? 'pmpu-scale' : 'pmpu'
})

// 响应式数据
const loading = ref(false);
const answerRecords = ref([]);
const totalRecords = ref(0);
const showDetailDialog = ref(false);
const showAnalysisDialog = ref(false);
const showDetailListDialog = ref(false);
const showAnswerDetailDialog = ref(false);
const selectedRecord = ref(null);
const selectedAnswerDetail = ref(null);
const detailList = ref([]);
const detailLoading = ref(false);

// 统计数据
const statistics = ref({
  totalRecords: 0,
  todayRecords: 0,
  activeUsers: 0,
});

// 搜索表单
const searchForm = reactive({
  userAnswerGroupId: undefined,
  questionnaireId: undefined,
  answerTime: undefined,
  status: undefined,
});

// 下载文件工具函数
const downloadBlobFile = (data, fileName) => {
  const blob = new Blob([data]);
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

const exportRecords = () => {
  userAnswerApi.exportUserAnswer(searchForm).then(res => {
    if (res) {
      downloadBlobFile(res.data, `问题性手机使用报告.xlsx`);
    } else {
      error.value = "下载报告失败";
    }
  });
};

// 状态选项
const statusOptions = ref([
  { label: "进行中", value: 0 },
  { label: "已完成", value: 1 },
  { label: "已放弃", value: 2 },
]);

// 获取答题记录列表
const getAnswerRecords = async () => {
  loading.value = true;
  try {
    const response = await userAnswerApi.getUserAnswerList(searchForm);
    if (response.success) {
      if (currentSystem.value === 'pmpu') {
        answerRecords.value = response.data.filter(item => item.userAnswerList.length === 1)
      } else if (currentSystem.value === 'pmpu-scale') {
        answerRecords.value = response.data.filter(item => item.userAnswerList.length === 2)
      } else {
        answerRecords.value = response.data.filter(item => item.userAnswerList.length === 5)
      }
    }
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "错误",
      detail: "获取答题记录失败",
      life: 3000,
    });
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const getStatistics = async () => {
  try {
    // 暂时使用模拟数据，因为后台没有统计接口
    statistics.value = {
      totalRecords: totalRecords.value,
      todayRecords: 0,
      activeUsers: 0,
    };
  } catch (error) {
    console.error("获取统计数据失败:", error);
  }
};

// 搜索记录
const searchRecords = () => {
  getAnswerRecords();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    username: "",
    questionnaireTitle: "",
    answerTime: null,
    status: null,
    pageNum: 1,
    pageSize: 10,
  });
  getAnswerRecords();
};

// 查看详细答题记录
const viewDetailList = async (id) => {
  detailLoading.value = true;
  showDetailListDialog.value = true;
  try {
    const response = await userAnswerApi.getUserAnswerDetailList(id);
    console.log("API响应数据:", response);

    // 确保数据是数组格式
    if (Array.isArray(response)) {
      detailList.value = response;
    } else if (response && Array.isArray(response.data)) {
      detailList.value = response.data;
    } else if (response && Array.isArray(response.records)) {
      detailList.value = response.records;
    } else {
      detailList.value = [];
    }

    console.log("处理后的数据:", detailList.value);
  } catch (error) {
    console.error("获取详细答题记录失败:", error);
    toast.add({
      severity: "error",
      summary: "错误",
      detail: "获取详细答题记录失败",
      life: 3000,
    });
    detailList.value = [];
  } finally {
    detailLoading.value = false;
  }
};

// 获取得分颜色
const getScoreColor = (score) => {
  if (!score) return "text-gray-500";
  if (score >= 90) return "text-green-600";
  if (score >= 80) return "text-blue-600";
  if (score >= 60) return "text-orange-600";
  return "text-red-600";
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "-";
  return new Date(date).toLocaleString("zh-CN");
};

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds) return "-";
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};

// 计算正确率
const calculateAccuracy = (record) => {
  if (!record.totalQuestions || record.totalQuestions === 0) return 0;
  return Math.round((record.correctAnswers / record.totalQuestions) * 100);
};

// 计算平均用时
const calculateAverageTime = (record) => {
  if (!record.duration || !record.totalQuestions || record.totalQuestions === 0)
    return 0;
  return Math.round(record.duration / record.totalQuestions);
};

// 获取因子值的样式类
const getFactorValueClass = (factorValue) => {
  if (!factorValue) return "bg-gray-100 text-gray-600";

  if (factorValue >= 4.0) return "bg-red-100 text-red-800";
  if (factorValue >= 3.0) return "bg-orange-100 text-orange-800";
  if (factorValue >= 2.0) return "bg-yellow-100 text-yellow-800";
  if (factorValue >= 1.0) return "bg-green-100 text-green-800";

  return "bg-blue-100 text-blue-800";
};

// 获取RE值的样式类
const getReNumClass = (reNum) => {
  if (!reNum) return "bg-gray-100 text-gray-600";

  if (reNum >= 0.8) return "bg-red-100 text-red-800";
  if (reNum >= 0.6) return "bg-orange-100 text-orange-800";
  if (reNum >= 0.4) return "bg-yellow-100 text-yellow-800";
  if (reNum >= 0.2) return "bg-green-100 text-green-800";

  return "bg-blue-100 text-blue-800";
};

// 获取SE值的样式类
const getSeNumClass = (seNum) => {
  if (!seNum) return "bg-gray-100 text-gray-600";

  if (seNum >= 0.8) return "bg-red-100 text-red-800";
  if (seNum >= 0.6) return "bg-orange-100 text-orange-800";
  if (seNum >= 0.4) return "bg-yellow-100 text-yellow-800";
  if (seNum >= 0.2) return "bg-green-100 text-green-800";

  return "bg-blue-100 text-blue-800";
};

// 格式化日期时间显示
const formatDateTime = (dateTime) => {
  if (!dateTime) return "-";
  const date = new Date(dateTime);
  const now = new Date();
  const diffTime = Math.abs(now - date);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays === 1) return "今天";
  if (diffDays === 2) return "昨天";
  if (diffDays <= 7) return `${diffDays} 天前`;
  
  return date.toLocaleDateString("zh-CN");
};

// 获取大五人格结果（过滤并排序）
const getPersonalityResults = (userAnswerList) => {
  if (!userAnswerList) return [];
  
  // 按照大五人格维度顺序排序
  const personalityOrder = ['外倾性', '宜人性', '尽责性', '神经质', '开放性'];
  
  return userAnswerList
    .filter(answer => answer.questionnaireTitle)
    .sort((a, b) => {
      const aIndex = personalityOrder.findIndex(p => a.questionnaireTitle.includes(p));
      const bIndex = personalityOrder.findIndex(p => b.questionnaireTitle.includes(p));
      return aIndex - bIndex;
    });
};

// 获取人格维度名称
const getPersonalityName = (title) => {
  if (!title) return '未知维度';
  
  if (title.includes('外倾性')) return '外倾性';
  if (title.includes('宜人性')) return '宜人性';
  if (title.includes('尽责性')) return '尽责性';
  if (title.includes('神经质')) return '神经质';
  if (title.includes('开放性')) return '开放性';
  
  return title;
};

// 获取人格维度颜色
const getPersonalityColor = (index) => {
  const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
  return colors[index % colors.length];
};

// 获取水平标签
const getLevelLabel = (coefficient) => {
  if (coefficient === null || coefficient === undefined) return 'N/A';
  if (coefficient < -1) return '较低';
  if (coefficient <= 1) return '中等';
  return '较高';
};

// 获取进度条宽度
const getProgressWidth = (coefficient) => {
  if (coefficient === null || coefficient === undefined) return 0;
  
  // 使用sigmoid函数将系数映射到0-100的范围
  const sigmoid = 1 / (1 + Math.exp(-coefficient));
  return sigmoid * 100;
};

// 计算综合评分
const calculateOverallScore = (userAnswerList) => {
  if (!userAnswerList || userAnswerList.length === 0) return 'N/A';
  
  const validAnswers = userAnswerList.filter(answer => answer.reNum !== null && answer.reNum !== undefined);
  if (validAnswers.length === 0) return 'N/A';
  
  const coefficients = validAnswers.map(answer => answer.reNum);
  
  // 计算平衡性得分（系数越接近0越平衡，最高40分）
  const balanceScore = coefficients.reduce((sum, coeff) => {
    const distance = Math.abs(coeff);
    return sum + Math.max(0, 40 - distance * 20);
  }, 0) / coefficients.length;
  
  // 避免极端值的惩罚（最高30分）
  const extremeScore = coefficients.reduce((sum, coeff) => {
    const penalty = Math.abs(coeff) > 2 ? 20 : 0;
    return sum + (30 - penalty);
  }, 0) / coefficients.length;
  
  // 适应性得分（中等范围内的系数更有利，最高30分）
  const adaptabilityScore = coefficients.reduce((sum, coeff) => {
    if (Math.abs(coeff) <= 1) return sum + 30;
    if (Math.abs(coeff) <= 1.5) return sum + 20;
    return sum + 10;
  }, 0) / coefficients.length;
  
  const totalScore = Math.round(balanceScore + extremeScore + adaptabilityScore);
  return Math.min(100, Math.max(0, totalScore));
};

// 组件挂载时获取数据
onMounted(() => {
  getAnswerRecords();
  getStatistics();
});
</script>

<style scoped>
/* 自定义样式 */
</style>
